const { Car } = require('../models');
const { getFileUrl, getFileUrls } = require('../utils/fileHelper');

// 创建车辆
exports.createCar = async (req, res) => {
    try {
        // 重构请求数据
        const carData = {
            // 基础字段直接获取
            brand: req.body.brand,
            model: req.body.model,
            level: req.body.level,
            type: req.body.type,
            dailyRate: Number(req.body.dailyRate),
            city: req.body.city,
            returnCities: Array.isArray(req.body.returnCities)
                ? req.body.returnCities
                : JSON.parse(req.body.returnCities || '[]'),
            location: req.body.location,
            description: req.body.description,

            // 构建 specifications 对象
            specifications: {
                length: req.body['specifications.length'] ? Number(req.body['specifications.length']) : undefined,
                width: req.body['specifications.width'] ? Number(req.body['specifications.width']) : undefined,
                height: req.body['specifications.height'] ? Number(req.body['specifications.height']) : undefined,
                seats: Number(req.body['specifications.seats']),
                trunkCapacity: req.body['specifications.trunkCapacity'] ? Number(req.body['specifications.trunkCapacity']) : undefined,
                powerType: req.body['specifications.powerType'],
                range: req.body['specifications.range'] ? Number(req.body['specifications.range']) : undefined,
                fuelConsumption: req.body['specifications.fuelConsumption'] ? Number(req.body['specifications.fuelConsumption']) : undefined
            },

            // 处理图片URL
            coverImage: req.files?.coverImage?.[0]?.url,
            images: req.files?.images?.map(file => file.url) || [],

            // 处理附加服务
            additionalServices: req.body.additionalServices ?
                (Array.isArray(req.body.additionalServices) ?
                    req.body.additionalServices.map(service =>
                        typeof service === 'string' ? JSON.parse(service) : service
                    ) :
                    JSON.parse(req.body.additionalServices.replace(/\r\n/g, ''))
                ) : []
        };

        // 移除 specifications 中的 undefined 值
        Object.keys(carData.specifications).forEach(key => {
            if (carData.specifications[key] === undefined) {
                delete carData.specifications[key];
            }
        });

        const car = await Car.create(carData);
        res.status(201).json({
            success: true,
            message: '车辆创建成功',
            data: car
        });
    } catch (error) {
        console.error('创建车辆错误:', error);
        res.status(500).json({
            success: false,
            message: '车辆创建失败',
            error: error.message
        });
    }
};

// 获取车辆列表（增加搜索和筛选功能）
exports.getCars = async (req, res) => {
    try {
        const {
            page = 1,
            limit = 10,
            brand,
            model,
            type,
            level,
            city,           // 取车城市
            returnCity,     // 还车城市（用户想要还车的城市）
            minPrice,
            maxPrice,
            powerType,
            seats,
            status = '可租'
        } = req.query;

        // 构建查询条件
        const query = {};

        // 基础信息筛选
        if (brand) query.brand = new RegExp(brand, 'i');
        if (model) query.model = new RegExp(model, 'i');
        if (type) query.type = type;
        if (level) query.level = level;
        if (city) query.city = city;
        // 如果指定了还车城市，查找包含该城市的车辆
        if (returnCity) query.returnCities = returnCity;
        if (status) query.status = status;

        // 价格范围筛选
        if (minPrice || maxPrice) {
            query.dailyRate = {};
            if (minPrice) query.dailyRate.$gte = Number(minPrice);
            if (maxPrice) query.dailyRate.$lte = Number(maxPrice);
        }

        // 详细参数筛选
        if (powerType) query['specifications.powerType'] = powerType;
        if (seats) query['specifications.seats'] = Number(seats);

        // 执行查询
        const cars = await Car.find(query)
            .skip((page - 1) * limit)
            .limit(parseInt(limit))
            .sort({ createdAt: -1 });

        // 获取总数
        const total = await Car.countDocuments(query);

        // 返回结果
        res.status(200).json({
            success: true,
            data: {
                cars,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    pages: Math.ceil(total / limit)
                },
                filters: {
                    // 返回当前使用的筛选条件
                    brand,
                    model,
                    type,
                    level,
                    city,
                    returnCity,
                    minPrice,
                    maxPrice,
                    powerType,
                    seats,
                    status
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取车辆列表失败',
            error: error.message
        });
    }
};

// 获取单个车辆详情
exports.getCar = async (req, res) => {
    try {
        const car = await Car.findById(req.params.id);
        if (!car) {
            return res.status(404).json({
                success: false,
                message: '车辆不存在'
            });
        }
        res.status(200).json({
            success: true,
            data: car
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取车辆详情失败',
            error: error.message
        });
    }
};

// 更新车辆信息
exports.updateCar = async (req, res) => {
    try {
        const car = await Car.findByIdAndUpdate(
            req.params.id,
            req.body,
            { new: true, runValidators: true }
        );

        if (!car) {
            return res.status(404).json({
                success: false,
                message: '车辆不存在'
            });
        }

        res.status(200).json({
            success: true,
            message: '车辆信息更新成功',
            data: car
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '更新车辆信息失败',
            error: error.message
        });
    }
};

// 删除车辆
exports.deleteCar = async (req, res) => {
    try {
        const car = await Car.findByIdAndDelete(req.params.id);

        if (!car) {
            return res.status(404).json({
                success: false,
                message: '车辆不存在'
            });
        }

        res.status(200).json({
            success: true,
            message: '车辆删除成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '删除车辆失败',
            error: error.message
        });
    }
}; 